//
//  FFWebViewController.h
//  Components
//
//  Created by IT.Bear on 16-8-25.
//  Copyright (c) 2016年 FashionFinger. All rights reserved.
//

#import "FFWebViewController.h"
#import "FFTipsView.h"
#import "FFReceiverMessageHandler.h"
#import "FFJPushManager.h"
#import "FFShareView.h"

#define isIOS9 [[[UIDevice currentDevice]systemVersion] floatValue] >= 9.0

@interface FFWebViewController ()<NSURLConnectionDelegate,WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>

@property (nonatomic, strong) NSMutableData *webData;
@property (nonatomic, strong) NSURLConnection *connection;
@property (nonatomic, strong) NSString *htmlString;

@end

@implementation FFWebViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        [self deleteWebCache];
        CGFloat screen_width = [UIScreen mainScreen].bounds.size.width;
        CGFloat screen_height = [UIScreen mainScreen].bounds.size.height;
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20,screen_width , screen_height - 20)];
        self.webView.scrollView.bounces = NO;
        self.webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        self.webView.UIDelegate = self;
        self.webView.navigationDelegate = self;
        
        NSString *token = [[NSUserDefaults standardUserDefaults] valueForKey:@"token"];
        NSString *string = @"";
        if (token) {
            string = [NSString stringWithFormat:@"window.token='%@'",token];
            WKUserScript * cookieScript = [[WKUserScript alloc]
                                           initWithSource: string
                                           injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
            [[self.webView configuration].userContentController addUserScript:cookieScript];
        }
       
        // again, use stringWithFormat: in the above line to inject your values programmatically
        [[self.webView configuration].userContentController addScriptMessageHandler:self name:@"setToken"];//注册一个name为aaa的js方法
        [[self.webView configuration].userContentController addScriptMessageHandler:self name:@"iOSCopy"];//注册一个name为aaa的js方法

        [[self.webView configuration].userContentController addScriptMessageHandler:self name:@"getToken"];//注册一个name为aaa的js方法
        
        [[self.webView configuration].userContentController addScriptMessageHandler:self name:@"handlerRecevierMessage"];//注册一个name为aaa的js方法

        [[self.webView configuration].userContentController addScriptMessageHandler:self name:@"setTags"];//注册一个name为aaa的js方法

        [[self.webView configuration].userContentController addScriptMessageHandler:self name:@"saveImage"];//注册一个name为aaa的js方法
        [[self.webView configuration].userContentController addScriptMessageHandler:self name:@"copyImage"];//注册一个name为aaa的js方法
        [[self.webView configuration].userContentController addScriptMessageHandler:self name:@"handlerShare"];//注册一个name为aaa的js方法
        [[self.webView configuration].userContentController addScriptMessageHandler:self name:@"handlerShareProduct"];//注册一个name为aaa的js方法


        self.webView.allowsBackForwardNavigationGestures =YES;//打开网页间的滑动返回
        if (isIOS9) {
            self.webView.allowsLinkPreview = YES;//允许预览链接
        }
        //        self.webView.scale = YES;
        self.webView.backgroundColor = [UIColor whiteColor];
        [self.webView configuration].preferences.javaScriptEnabled = YES;
        [self.webView configuration].preferences.javaScriptCanOpenWindowsAutomatically = YES;
        [self.view addSubview:self.webView];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlerJump:) name:@"jumpeJmessage" object:nil];
        
    }
    return self;
}


- (id)initWithLoadData:(NSData *)data MIMEType:(NSString *)type characterEncodingName:(NSString *)encodingName baseUrl:(NSURL *)url
{
    self = [super init];
    if (self) {
        [self.webView loadData:data MIMEType:type characterEncodingName:encodingName baseURL:url];
    }
    return self;
}

- (id)initWithURL:(NSURL *)url {
    self = [super init];
    if (self) {
        [self loadURL:url];
    }
    return self;
}

- (id)initWithHTMLString:(NSString *)htmlString{
    self = [super init];
    if (self) {
        [self loadURL:nil htmlString:htmlString];
    }
    return self;
}

- (id)initWithURL:(NSURL *)url htmlString:(NSString *)htmlString {
    self = [super init];
    if (self) {
        self.htmlString = htmlString;
        [self loadURL:url htmlString:htmlString];
    }
    return self;
}

- (NSMutableURLRequest *)buildRequest {
    if (self.url) {
        return [NSMutableURLRequest requestWithURL:self.url];
    }else{
        return nil;
    }
}

- (void)loadURL:(NSURL *)url {
    [self loadURL:url htmlString:nil];
}

- (void)loadURL:(NSURL *)url htmlString:(NSString *)htmlString {
    if (url) {
        self.url = url;
    }
    
    NSMutableURLRequest *request = [self buildRequest];
    [request setTimeoutInterval:15];
    __block NSHTTPURLResponse *response = nil;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-variable"
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //在多线程中执行的代码
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
       
        //异步返回主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            if (response.statusCode == 404 || !response || response.statusCode == 500) {
                // 这里处理 404 代码
                
            } else if (response.statusCode == 403) {
                // 这里处理 403 代码
            }
        });
    });
   
#pragma clang diagnostic pop

    //UIWebView兼容https的方法
    if (htmlString) {
        if (!self.url) {
            [self.webView loadHTMLString:htmlString baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
        }else
            [self.webView loadHTMLString:htmlString baseURL:url];
    }else{
        //            if (isIOS9) {
        //                [self.webView loadData:data MIMEType:@"text/html" characterEncodingName:@"UTF-8" baseURL:self.url];
        //            }else{
        [self.webView loadRequest:request];
        //            }
    }
}

- (void)loadUserUIWebViewWithURL:(NSURL *)url htmlString:(NSString *)htmlString
{
    //UIWebView兼容https的方法
    NSURLRequest *request = [self buildRequest];
    if ([url.scheme isEqualToString:@"https"] && [self handleHttps]) {
        _connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
        [_connection start];
    }else{
        if (htmlString) {
            if (!self.url) {
                [self.webView loadHTMLString:htmlString baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
            }else
                [self.webView loadHTMLString:htmlString baseURL:url];
        }else{
            //            [self.webView loadData:data MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:self.url];
            //            if (isIOS9) {
            //                [self.webView loadData:data MIMEType:@"text/html" characterEncodingName:@"UTF-8" baseURL:self.url];
            //            }else{
            [self.webView loadRequest:request];
        }
    }
}

- (NSDictionary *)pasingWithString:(NSString *)string {
    NSString *urlStr = [NSString stringWithString:string];
    NSString *prefix = @"ffapp://";
    
    if ([[urlStr lowercaseString] hasPrefix:prefix]) {
        urlStr = [urlStr substringFromIndex:prefix.length];
        urlStr = [urlStr stringByRemovingPercentEncoding];
        NSError *error;
        NSDictionary *info = [NSJSONSerialization
                              JSONObjectWithData:[urlStr dataUsingEncoding:NSUTF8StringEncoding]
                              options:kNilOptions
                              error:&error];
        if([info count] > 0){
            return info;
        }
    }
    return nil;
}

- (BOOL)parseURLString:(NSString *)url {
    BOOL isHttps = [url hasPrefix:@"https"];
    if (isHttps) {
        [self loadURL:[NSURL URLWithString:url]];
    }
    return !isHttps;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (BOOL)handleHttps {
    return YES;
}

- (void)dismissViewController
{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - UIWebViewDelegate Methods

// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    //    [self parseURLString:webView.URL.absoluteString];
}

// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
   }
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
//    [self tokenToH5];
}

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation
{
    
}

- (void)webViewReload
{
    
}

- (void)postToken
{
//    NSString *token = [FFCache queryCache:USER_TOKEN];
//    NSString *uid = [[FFLocalCacheManager sharedInstance] getCacheUserInfo].userId;
//    NSString *scripMethod = [NSString stringWithFormat:@"iosappSetToken('%@','%@')",uid,token];
//    if (token.length > 0 && uid.length > 0) {
//        [self.webView evaluateJavaScript:scripMethod completionHandler:^(id response, NSError * _Nullable error) {
//
//        }];
//    }else{
//        NSString *scripMethod = [NSString stringWithFormat:@"iosappSetToken('%@','%@')",@"",@""];
//        [self.webView evaluateJavaScript:scripMethod completionHandler:^(id response, NSError * _Nullable error) {
//        }];
//    }
}

-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message

{
    //    userContentController 注册message的WKUserContentController；
    //    message：js传过来的数据
    //    id body:消息携带的信息 Allowed types are NSNumber, NSString, NSDate, NSArray, NSDictionary, and NSNull.
    //    NSString *name:消息的名字 如aaa
    
    //message.name  js发送的方法名称
    if ([message.name isEqualToString:@"setToken"]) {
        //web需要header
        NSString *urlStr = message.body;
        [[NSUserDefaults standardUserDefaults] setObject:urlStr forKey:@"token"];
    }
    if ([message.name isEqualToString:@"getToken"]) {
        NSString *token = [[NSUserDefaults standardUserDefaults] valueForKey:@"token"];
        NSString *scripMethod = [NSString stringWithFormat:@"sendToken('%@')",token];
        [self.webView evaluateJavaScript:scripMethod completionHandler:^(id response, NSError * _Nullable error) {
            
        }];
    }
    if ([message.name isEqualToString:@"iOSCopy"]) {
        //web需要header
        NSString *content = message.body;
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = content;
        [FFTipsView showTips:@"已复制到粘贴板"];
    }
    if ([message.name isEqualToString:@"handlerRecevierMessage"]) {
        [[FFReceiverMessageHandler sharedInstance] handlerReceiver];
    }
    if ([message.name isEqualToString:@"setTags"]) {
        NSString *content = message.body;
        [[FFJPushManager sharedInstance] addTags:content];
    }
    if ([message.name isEqualToString:@"saveImage"]) {
        NSString *url = message.body;
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];
        if (image) {
             [self loadImageFinished:image];
        }
    }
    if ([message.name isEqualToString:@"copyImage"]) {
        NSString *url = message.body;
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];
        [self copyImage:image];
    }
    if ([message.name isEqualToString:@"handlerShare"]) {
        NSString *imageUrl = message.body;
        UIImage *coverImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]]];
        FFShareView *share = [[FFShareView alloc] initWithFrame:[UIApplication sharedApplication].keyWindow.bounds];
        NSString *shareText = @"";
        [share showWithSnsSheetView:self shareTitle:@"" shareText:shareText shareImage:coverImage shareUrl:@"" callBack:^(BOOL sucessful, NSString *snsName) {
            
        }];
    }
    if ([message.name isEqualToString:@"handlerShareProduct"]) {
        NSString *urlStr = message.body;
        if (urlStr) {
            NSError *error;
            NSData *data = [urlStr dataUsingEncoding:NSUTF8StringEncoding];
            
            NSDictionary *info;
            if (data) {
                info = [NSJSONSerialization
                        JSONObjectWithData:data
                        options:kNilOptions
                        error:&error];
            }
            if([info count] > 0){
                NSString *imageUrl = info[@"cover"];
                NSString *title = info[@"shareTitle"];
                NSString *text = info[@"shareText"];
                NSString *shareUrl = info[@"shareUrl"];
                UIImage *coverImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]]];
                FFShareView *share = [[FFShareView alloc] initWithFrame:[UIApplication sharedApplication].keyWindow.bounds];
                
                [share showWithSnsSheetView:self shareTitle:title shareText:text shareImage:coverImage shareUrl:shareUrl callBack:^(BOOL sucessful, NSString *snsName) {
                    
                }];
            }
        }
        
    }
    
}

//复制图片
-(void)copyImage:(UIImage *)image
{
    UIPasteboard *pboard = [UIPasteboard generalPasteboard];
    pboard.image = image;
}

- (void)loadImageFinished:(UIImage *)image
{
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (!error) {
        [FFTipsView showTips:@"已保存到相册"];
    }else{
        [FFTipsView showTips:@"保存失败"];
    }
    
    NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
}

- (void)handlerJump:(NSNotification *)notification
{
    if (notification.userInfo) {
        NSString *jmessageName = notification.userInfo[@"jmessageName"];
        NSString * string = [NSString stringWithFormat:@"window.router.push('/dialogue/%@')",jmessageName];
        WKUserScript * cookieScript = [[WKUserScript alloc]
                                       initWithSource: string
                                       injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
        [[self.webView configuration].userContentController addUserScript:cookieScript];
    }
}

#pragma mark - HTTPS  NSURLConnectionDelegate --UIWebView用的方法
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
        [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]
             forAuthenticationChallenge:challenge];
    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    if (self.webData == nil) {
        self.webData = [[NSMutableData alloc] init];
    }
    [self.webData appendData:data];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    if (_htmlString) {
        [self.webView loadHTMLString:_htmlString baseURL:nil];
    }else{
        [self.webView loadData:self.webData MIMEType:@"text/html" characterEncodingName:@"GBK" baseURL:nil];
        //        [self.webView loadData:self.webData MIMEType:@"text/html" characterEncodingName:@"UTF-8" baseURL:nil];
        //        [self.webView loadData:self.webData MIMEType: @"text/html" textEncodingName: @"UTF-8" baseURL:nil];
    }
}

-(WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    //    DLOG(@"msg = %@ frmae = %@",message,frame);
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }])];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];
    
}

//WKWebView https请求权限认证
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        if ([challenge previousFailureCount] == 0) {
            NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
            completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
        } else {
            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
        }
    } else {
        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
    }
}

// https 支持
//- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
//
//    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
//
//        NSURLCredential *card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
//
//        completionHandler(NSURLSessionAuthChallengeUseCredential,card);
//
//    }
//}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [_connection cancel];
    [[self.webView configuration].userContentController removeScriptMessageHandlerForName:@"actionFromWeb"];
    [self.webView stopLoading];
    
}

- (void)deleteWebCache
{
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
        //        NSSet *websiteDataTypes
        //        = [NSSet setWithArray:@[
        //                                WKWebsiteDataTypeDiskCache,
        //                                //WKWebsiteDataTypeOfflineWebApplicationCache,
        //                                WKWebsiteDataTypeMemoryCache,
        //                                //WKWebsiteDataTypeLocalStorage,
        //                                //WKWebsiteDataTypeCookies,
        //                                //WKWebsiteDataTypeSessionStorage,
        //                                //WKWebsiteDataTypeIndexedDBDatabases,
        //                                //WKWebsiteDataTypeWebSQLDatabases
        //                                ]];
        //// All kinds of data
        NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
        //// Date from
        NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
        //// Execute
        [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
            // Done
        }];
        
    }
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
